package com.zhou.common.lib.util;

import com.google.common.collect.Lists;
import com.zhou.common.lib.model.ImageVo;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Slf4j
public class ShortcutIconUtils {

    private static final OkHttpClient client = new OkHttpClient();


    public static ImageVo getIcon(String path) {
        byte[] bytes = null;
        String imgPath = null;
        Document doc = test(path);
        if (doc != null) {
            imgPath = getIconUrl(doc, path);
            if (StringUtils.isEmpty(imgPath)) {
                imgPath = HttpUtil.getBasePath(path) + "/favicon.ico";
            }
            if (StringUtils.isNotEmpty(imgPath)) {
                String host = HttpUtil.getHost(imgPath);
                String fileName = HttpUtil.getFileName(imgPath);
                Request request = new Request.Builder().url(imgPath).build();
                Response response = null;
                try {
                    response = client.newCall(request).execute();
                    bytes = response.body().bytes();
                } catch (IOException e) {
                    log.error("", e);
                }
                response.close();
            }
        }
        if (bytes != null) {
            log.info("获取成功{}", path);
            return new ImageVo(bytes, imgPath);
        } else {
            log.info("获取失败{}", path);
            return null;
        }
    }

    public static void main(String[] args) throws Exception {

        String basePath = "common-lib/imgs/";
        File dir = new File(basePath);
        if (!MyFileUtils.isDirectory(dir)) {
            MyFileUtils.forceMkdir(dir);
        }
        List<String> paths = Lists.newArrayList(
                "https://www.baidu.com/",
                "http://172.21.193.133/nacos-test/#/configurationManagement?dataId=&group=&appName=&namespace=&pageSize=&pageNo=",
                "https://fanyi.baidu.com/translate#en/zh/jumbotron",
                "https://v3.bootcss.com/css/#grid",
                "https://cloud.tencent.com/developer/article/2149113",
                "http://Fanyi.baidu.com/translate"
        );
        for (String path : paths) {
            Document doc = test(path);
            if (doc != null) {
                String imgPath = getIconUrl(doc, path);
                if (StringUtils.isEmpty(imgPath)) {
                    imgPath = HttpUtil.getBasePath(path) + "/favicon.ico";
                }
                if (StringUtils.isNotEmpty(imgPath)) {
                    String host = HttpUtil.getHost(imgPath);
                    String fileName = HttpUtil.getFileName(imgPath);
                    Request request = new Request.Builder().url(imgPath).build();
                    Response response = client.newCall(request).execute();
                    MyFileUtils.fileWriter(response.body().bytes(), basePath + host + fileName);
                    log.info("获取成功{}", path);
                    response.close();
                    continue;
                }
            }
            log.info("获取失败{}", path);
        }
    }

    public static String getIconUrl(Document doc, String basePath) {
        Element shortcutIcon = doc.selectFirst("link[rel='shortcut icon']");
        if (shortcutIcon == null) {
            return null;
        }
        log.info("link={}", shortcutIcon);
        String url = shortcutIcon.attr("href");
        log.info("parturl={}", url);
        if (StringUtils.isEmpty(url)) {
            return null;
        }
        return HttpUtil.getFullUlr(basePath, url);
    }

    public static Document test(String url) {

        Document parse = null;
        try {
            parse = Jsoup.connect(url).timeout(5000).get();
        } catch (IOException e) {
            log.info("", e);
        }
        return parse;
    }
}
